import sys

import paramiko


class SshRun:
    def __init__(self):
        pass

    @staticmethod
    def ssh_connect(ip, username, password):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, 22, username, password, timeout=1800,
                    allow_agent=False, look_for_keys=False)
        return ssh

    @staticmethod
    def ssh_run(ssh, command):
        print(command)
        stdin, stdout, stderr = ssh.exec_command(command)
        run_res = stdout.read().decode('utf-8').strip()
        er_res = stderr.read().decode('utf-8').strip()
        if er_res:
            print(f'ERROR:{er_res}')
        if run_res:
            print(f'SUCCESS:{run_res}')
        return run_res

    @staticmethod
    def ssh_close(ssh):
        ssh.close()


if __name__ == '__main__':
    ip_all = ["", ""]
    pwd = sys.argv[1]
    my_sh = SshRun()
    user_prefix = ('func_1_', 'func_2_', 'func_3_', 'func_4_', 'func_pb_')
    jenkins_nodes_dict = {
        "host": "jenkins_connect_url"
         }

    # 如jenkins连接断开，则重连
    for k, v in jenkins_nodes_dict.items():
        print(k)
        conn = my_sh.ssh_connect(k, 'root', pwd)
        cmd = "ps -ef|grep jenkins-agent.jnlp|grep -v grep|wc -l"
        num = my_sh.ssh_run(conn, cmd)
        if num and int(num) < 1:
            v = v.replace('agent.jar', '/autotest_software/jenkins/agent.jar')
            cmd = f"nohup {v} > run_jenkins.log 2>&1 &"
            my_sh.ssh_run(conn, cmd)
        my_sh.ssh_close(conn)

    cmd = ''
    for u in user_prefix:
        # '清理互信定时任务'
        cmd += f"rm -rf /var/spool/cron/{u}*;"
        # '杀进程'
        cmd += f"ps -ef|grep -vE 'grep|jenkins'|grep {u}|" \
            f"awk '{{print $2}}'|xargs -I {{}} kill -9 {{}};"
        # '清理共享内存'
        cmd += f"ipcs -m|grep {u}|awk '{{print $2}}'|" \
            f"xargs -I {{}} ipcrm -m {{}};"
        # '清理信号量'
        cmd += f"ipcs -s|grep {u}|awk '{{print $2}}'|" \
            f"xargs -I {{}} ipcrm -s {{}};"
        # '清理磁盘'
        cmd += f"rm -rf /home/{u}* /opt/{u}* /root/gauss_om/{u}* /data/{u}*;"

    # '清理可能残存的press进程'
    cmd += "ps -ef|grep press_64|grep -v grep|awk '{print $2}'|" \
           "xargs -I {} kill -9 {};"
    # '清理可能残存的定时任务'
    cmd += '''if [ -e /var/spool/cron/root ]
        then
            sed -i '/get_date.sh/d' /var/spool/cron/root
            sed -i '/check_port.sh/d' /var/spool/cron/root
        fi;'''
    cmd += "ps -ef|grep check_port.sh|grep -v grep|awk '{print $2}'|" \
           "xargs -I {} kill -9 {};"
    cmd += "ps -ef|grep get_date.sh|grep -v grep|awk '{print $2}'|" \
           "xargs -I {} kill -9 {};"
    # '清理内存'
    cmd += "sync;" \
           "echo 3 > /proc/sys/vm/drop_caches;"
    # '清理系统日志，只保留最近一周的'
    cmd += "find /var/log -type f -daystart -mtime +7 -print -delete;"
    # '删除旧的codehub拉取文件，清理磁盘'
    cmd += "rm -rf /home/codehub/testcase_*;"
    # '查看内存'
    cmd += "free -h|grep Mem|awk '{print $4}';"
    cmd += "ps -ef|grep press_64|grep -v grep|wc -l;"

    cmd += 'free -h;'
    cmd += 'echo -e "\n\n\n";'
    for i in ip_all:
        print(f'当前主机：{i}')
        conn = my_sh.ssh_connect(i, 'root', pwd)
        for c in cmd.split(';'):
            if len(c.strip()) > 0:
                my_sh.ssh_run(conn, c)

        print('配置端口号取值范围，以避免对数据库端口占用')
        grep_cmd = "grep 'net.ipv4.ip_local_port_range' /etc/sysctl.conf"
        res = my_sh.ssh_run(conn, grep_cmd)
        add_cmd = None
        if 'No such file or directory' in res:
            raise Exception('Error: 请检查文件!')
        elif len(res.strip()) == 0:
            add_cmd = 'echo "net.ipv4.ip_local_port_range = 20000 39999" ' \
                      '>> /etc/sysctl.conf;'
        else:
            add_cmd = "sed -i '/^net.ipv4.ip_local_port_range/" \
                      "cnet.ipv4.ip_local_port_range = 20000 39999' " \
                      "/etc/sysctl.conf;"
        if add_cmd:
            add_cmd += "sysctl -p /etc/sysctl.conf;"
            my_sh.ssh_run(conn, add_cmd)

        my_sh.ssh_close(conn)
